package Producer_and_Customer;

/**
 * 生产者消费者模式:线程通信
 * -->利用缓冲区解决：管程法
 * @author luyao_start
 * @create 2021-08-19-23:27
 */
public class ProducerAndCustomer {
    public static void main(String[] args) {
        synContainer synContainer = new synContainer();
        new Producer(synContainer).start();
        new Customer(synContainer).start();
    }
}

//生产者
class Producer extends Thread{
    synContainer container;

    public Producer(synContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            container.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
        }
    }
}

//消费者
class Customer extends Thread{
    synContainer container;

    public Customer(synContainer container) {
        this.container = container;
    }

    @Override
    public void run() {

        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->"+container.pop().id+"只鸡");
        }
    }
}

//产品
class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

//缓冲区
class synContainer{
    Chicken[] chickens = new  Chicken[10];
    int count = 0;

    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //容器满了，需要消费者消费
        if(count == chickens.length){
            //通知消费者消费,生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果没有满,丢入商品
        chickens[count] = chicken;
        count++;

        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        if(count == 0){
            //通知生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickens[count];

        this.notifyAll();

        return chicken;
    }
}
